# -*- coding: UTF-8 -*-
from Code.Utils.sc_func import Common, Singleton, JsonParser
from Code.Model.sc_global import Global
from Code.Model.Data.sc_data import (model_gate,
                                     wrapper_exception,
                                     SettingsDataError,
                                     DependenceDataError,
                                     LanguageDataError
                                     )
from Code.Model.Controller.sc_logger import logger


@Singleton
class Loader(object):

    @wrapper_exception
    def check_file(self):
        Global.G_PID_DIR = "{}\\{}".format(Global.G_RUN_DIR, Common.get_pid())
        Common.mkdir(Global.G_RUN_DIR)
        Common.mkdir(Global.G_DOWNLOAD_DIR)
        Common.mkdir(Global.G_PID_DIR)
        logger.info('SystemController start')

        for path in [Global.G_RESOURCE_DIR, Global.G_DEPENDENCE_FILE, Global.G_SETTINGS_FILE, Global.G_LANGUAGE_FILE,
                     Global.G_SCRIPTS_DIR]:
            if not Common.is_exists(path):
                raise FileNotFoundError("{} is not exist".format(path))
        return True

    @wrapper_exception
    def json_parser(self, reload=False):
        _except = Exception
        try:
            _except = LanguageDataError
            # dependence.json解析和数据初始化
            model_gate.language_data.load(JsonParser.load(Global.G_LANGUAGE_FILE))

            _except = SettingsDataError
            # settings.json解析和数据初始化
            model_gate.settings_data.load(JsonParser.load(Global.G_SETTINGS_FILE))

            _except = DependenceDataError
            # languages.json解析和数据初始化
            model_gate.dependence_data.load(JsonParser.load(Global.G_DEPENDENCE_FILE), reload)
        except Exception as e:
            raise _except(str(e))
        return True

    def settings_writer(self, key, value):
        try:
            settings = JsonParser.load(Global.G_SETTINGS_FILE)
            settings['Settings'][key] = value
            JsonParser.write(Global.G_SETTINGS_FILE, settings)
        except Exception as e:
            raise SettingsDataError(str(e))

    def init(self):
        return self.check_file() and self.json_parser()

    @classmethod
    def close(cls, data=None):
        Common.rm_dir(Global.G_PID_DIR)
        Common.remove(Global.G_INFO_PATH)


loader = Loader()

